//和用户相关的状态管理
import { removeToken, request } from "@/utils"
import { createSlice } from "@reduxjs/toolkit"
import { getToken, setToken as _setToken } from "@/utils"
import { loginApi } from "@/apis/adminuser"
import {  getProfileApi } from "@/apis/adminuser"


const useStore = createSlice({
    name: "user",
    initialState: {
        token: getToken("user_token") || '',
        userInfo: {}
    },
    //同步方法修改
    reducers: {
        setToken(state, action) {
            state.token = action.payload
            // const res =  loginApi(action.payload)
            // state.token = "xxx"
            // _setToken("user_token", "xxx")
            // console.log(1)
        },
        //同步方法
        setUserInfo(state, action) {
            // console.log(action.payload)
            state.userInfo = action.payload
        },
        //清除用户登录信息
        clearUserInfo(state, action) {
            state.userInfo = {}
            state.token = ""
            removeToken("user_token")
        }
    }
})

//action
const { setToken, setUserInfo, clearUserInfo } = useStore.actions

//reducer
const useReducer = useStore.reducer

//异步登录方法
const fetchLogin = (loginfrom) => {
    return async (dispatch) => {
        const res = await loginApi(loginfrom)
        if (res.code == 200) {
            dispatch(setToken(res.data))
            _setToken("user_token", res.data)

        }
        return res
    }
}

//获取用户信息
const fetchUserInfo = () => {
    return async (dispatch) => {
        const res = await getProfileApi()
        if (res.code == 200){
            dispatch(setUserInfo(res.data))
        }
        return res
    }
}


export default useReducer
export { setToken, fetchLogin, fetchUserInfo, clearUserInfo }